package logic

import (
	"context"
	"fmt"
	"user_srv/cache"
	"user_srv/mysql"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var u mysql.User
	u.Mobile = in.Mobile
	err = u.FindUserByMobile()
	if err != nil {
		logx.Error("用户不存在 登录失败:", err)
		return nil, err
	}

	//如果未注册 注册
	if u.ID == 0 {
		err = u.Create()
		if err != nil {
			logx.Error("注册失败:", err)
			return nil, err
		}
	}

	get := cache.Rdb.Get(l.ctx, "SendSms"+in.Mobile).Val()
	if in.SendSmsCOde != get {
		return nil, fmt.Errorf("验证码输入错误")
	}

	return &user.LoginResponse{
		Id: int64(u.ID),
	}, nil
}
